package com.ztewatch.wearcontacts.presenter;

import java.util.ArrayList;

import com.ztewatch.wearcontacts.data.SimpleContactData;
import com.ztewatch.wearcontacts.loader.ContactsListLoader;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri.Builder;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;

public class LGUContactDataPresenter {
	public static final String LGU_PHONEBOOK_SENDBROADCAST_ACTION = "com.LGU.kidswatch.receiver.OP_RESP";
	public static final String LGU_PHONEBOOK_GETBROADCAST_ACTION = "com.LGU.kidswatch.receiver.ADDRBOOK_OP";
	public static final String CONTACT_LIST_EXTRA = "contact_list_extra";
	public static final String CONTACT_ACTION_FLAG = "contact_action_flag";
	public static final int ADD_CONTACT_FLAG = 0;
	public static final int EDIT_CONTACT_FLAG = 1;
	public static final int DELETE_CONTACT_FLAG = 2;

	private Context mContext;

	public LGUContactDataPresenter(Context context) {
		mContext = context;
	}

	public void doBroadCastFromLGUApp(int contact_action_flag) {

	}

	public void sendBroadCastToLGUApp(int contact_action_flag) {
		Intent intent = new Intent();
		intent.setAction(LGU_PHONEBOOK_SENDBROADCAST_ACTION);
		ArrayList<SimpleContactData> mContactDatas = new ArrayList<SimpleContactData>();

		// query contact list start
		final Builder builder = Data.CONTENT_URI.buildUpon();
		StringBuilder selection = new StringBuilder();
		selection.append(Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE
				+ "','" + Email.CONTENT_ITEM_TYPE + "')");
		builder.appendQueryParameter(ContactsContract.REMOVE_DUPLICATE_ENTRIES,
				"true");
		Cursor c = mContext.getContentResolver().query(builder.build(),
				ContactsListLoader.CONTACTS_SUMMARY_PROJECTION,
				selection.toString(), null,
				Data.DISPLAY_NAME_PRIMARY + " COLLATE LOCALIZED ASC");
		if (c != null && c.getCount() != 0) {
			c.moveToPosition(-1);
			while (c.moveToNext()) {
				String name = c.getString(ContactsListLoader.NAME_COLUMN_ID);
				long id = c.getLong(ContactsListLoader.ID_COLUMN_ID);
				String number = c
						.getString(ContactsListLoader.NUMBER_COLUMN_ID);
				SimpleContactData contactData = new SimpleContactData(id, name,
						number);
				mContactDatas.add(contactData);
			}
		}
		// query contact list end

		intent.putExtra(CONTACT_LIST_EXTRA, mContactDatas);
		intent.putExtra(CONTACT_ACTION_FLAG, contact_action_flag);
		mContext.sendBroadcast(intent);
	}
}
